<?php

require_once dirname(__FILE__).'/sfTaskExtraAddon.class.php';

/**
 * Adds functionality to build model tasks.
 * 
 * @package     sfTaskExtraPlugin
 * @subpackage  task
 * @author      Kris Wallsmith <kris.wallsmith@symfony-project.com>
 * @version     SVN: $Id: sfTaskExtraBuildModelAddon.class.php 15353 2009-02-08 21:12:33Z Kris.Wallsmith $
 */
class sfTaskExtraBuildModelAddon extends sfTaskExtraAddon
{
  /**
   * @see sfTaskExtraAddon
   */
  public function executeAddon($arguments = array(), $options = array())
  {
    $finder = sfFinder::type('file')->maxdepth(0);
    foreach ($finder->in($this->pluginConfiguration->getConnectedPluginSubPaths('/lib/model')) as $file)
    {
      if (
        !file_exists($pluginFile = dirname($file).'/plugin/Plugin'.basename($file))
        &&
        preg_match('/(\w+) extends (\w+)/', $contents = file_get_contents($file), $match)
        &&
        0 !== strpos($match[2], 'Plugin')
      )
      {
        $pluginContents = <<<EOF
<?php

/**
 * Plugin model class generated by sfTaskExtraPlugin.
 */
class Plugin{$match[1]} extends $match[2]
{
}

EOF;

        // create plugin class
        $this->getFilesystem()->mkdirs(dirname($pluginFile));
        $this->getFilesystem()->touch($pluginFile);
        file_put_contents($pluginFile, $pluginContents);

        // edit stub class
        $this->logSection('edit', $file);
        file_put_contents($file, str_replace('extends '.$match[2], 'extends Plugin'.$match[1], $contents));
      }
    }
  }
}
